#include <windows.h>
#include "lua_library.h"
#include "lua_library/lua_utils.h"
#include "lua_library/lua_print.h"
#include "lua_library/lua_json.h"
#include "lua_library/lua_network.h"
#include "lua_library/lua_path.h"
#include "lua_library/lua_thread.h"
#include "lua_library/lua_share.h"
#include "lua_library/lua_bitop.h"
#include "lua_library/lua_str.h"

#include <string>

static luaL_Reg lib_functions[] =
{
    { "sleep", &lua_library::sleep},
    { "print", &lua_print::print},
    { NULL, NULL}
};

int
#ifdef _WIN64
luaopen_lua_library(lua_State* L)
#else
luaopen_lua_library(lua_State * L)
#endif
{
    lua_newtable(L);
    lua_json::initialize(L, "json");
    lua_network::initialize(L, "network");
    lua_path::initialize(L, "path");
    //lua_thread::initialize(L, "thread");
    lua_share::initialize(L, "share");
    lua_bitop::initialize(L, "bitop");
    lua_str::initialize(L, "str");

    luaL_Reg* fun_info = lib_functions;
    while (fun_info->func)
    {
        lua_pushcfunction(L, fun_info->func);
        lua_setfield(L, -2, fun_info->name);
        fun_info++;
    }

    return 1;
}

void close_lua_library()
{
    //lua_thread::uninitialize();
    lua_path::uninitialize();
    lua_network::uninitialize();
    lua_json::uninitialize();
    lua_share::uninitialize();
    lua_bitop::uninitialize();
    lua_str::uninitialize();
}

int lua_library::sleep(lua_State* L)
{
    int nTop = lua_gettop(L);
    if (nTop >= 1 && lua_isnumber(L, -1))
    {
        ::Sleep(lua_tointeger(L, -1));
    }

    return 0;
}
